package com.itheima.service.imlp;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.Mapper.CategoryMapper;
import com.itheima.Mapper.DishMapper;
import com.itheima.Mapper.SetmealMapper;
import com.itheima.entity.Category;
import com.itheima.entity.Dish;
import com.itheima.entity.Setmeal;
import com.itheima.exection.DeleteByIdDishCustomExection;
import com.itheima.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class CategoryServiceImpl
        extends ServiceImpl<CategoryMapper, Category>
        implements ICategoryService {

    //    此处注入持久层属性
    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private SetmealMapper setmealMapper;


    @Override
    public boolean deleteByIdDishCustom(Long id) {
        //1、检查当前分类下是否有对应的菜品
        // SELECT COUNT(*) FROM `dish` WHERE category_id = 1397844263642378242
        // 结果大于0 ，则不能删除  代码结束 return R.error("当前分类下有菜品，不能删除")
        LambdaQueryWrapper<Dish> wrapper = new LambdaQueryWrapper<>();
//        把前端传过来的id与Dish类中的id进行比对
        wrapper.eq(Dish::getCategoryId, id);
        Integer count = dishMapper.selectCount(wrapper);
        if (count > 0) {
            throw new DeleteByIdDishCustomExection("当前分类下有菜品，不能删除");

        }

        //2、检查当前分类下是否有对应的套餐
        // SELECT COUNT(*) FROM `setmeal` WHERE category_id= 1397844263642378242
        //结果大于0 ，则不能删除  代码结束 return R.error("当前分类下有套餐，不能删除")
        LambdaQueryWrapper<Setmeal> wrapper1 = new LambdaQueryWrapper<>();
        wrapper1.eq(Setmeal::getCategoryId,id);
        Integer count2 = setmealMapper.selectCount(wrapper1);

        if (count2>0){
            throw new DeleteByIdDishCustomExection("当前分类下有套餐，不能删除");
        }


        //3、可以删除,则调用mapper直接删除 categoryMapper.deleteById(id);
        super.removeById(id);
        return true;

    }

}
